<template>
  <a-card>
    <!-- 查询 -->
    <a-form
        ref="searchFormRef"
        :model="search_form"
        @submit="handleSearchSubmit"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
    >
      <a-row>
        <a-col :flex="1">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="申请人" field="userId">
                <!--                <a-input placeholder="请输入申请人ID" v-model="search_form.userId"></a-input>-->
                <a-select v-model="search_form.userId" placeholder="请选择申请人">
                  <a-option v-for="user in users" :key="user.userIdWbxqy" :value="user.userIdWbxqy">
                    {{ user.usernameWbxqy }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="车辆" field="carId">
                <!--                <a-input placeholder="请输入车辆ID" v-model="search_form.carId"></a-input>-->
                <a-select v-model="search_form.carId" placeholder="请选择车辆">
                  <a-option v-for="car in cars" :key="car.carIdWbxqy" :value="car.carIdWbxqy">
                    {{ car.licensePlateWbxqy }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="司机" field="driverId">
                <!--                <a-input placeholder="请输入司机ID" v-model="search_form.driverId"></a-input>-->
                <a-select v-model="search_form.driverId" placeholder="请选择司机">
                  <a-option v-for="driver in drivers" :key="driver.userIdWbxqy" :value="driver.userIdWbxqy">
                    {{ driver.usernameWbxqy }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-divider style="height: 84px" direction="vertical"/>
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search/>
              </template>
              查询
            </a-button>
            <a-button @click="$refs.searchFormRef.resetFields()">
              <template #icon>
                <icon-refresh/>
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <!-- 信息展示 -->
    <a-table :columns="columns" :data="requests" :pagination="pagination" @page-change="handlePaginationChange" style="height: 70vh">
      <template #user="{record, rowIndex}">
        {{ record.user.usernameWbxqy }}
      </template>
      <template #car="{record, rowIndex}">
        {{ record.car !== null ? record.car.licensePlateWbxqy : "未分配车辆" }}
      </template>
      <template #driver="{record, rowIndex}">
        {{ record.driver !== null ? record.driver.usernameWbxqy : "未分配司机" }}
      </template>
      <template #status="{ record,rowIndex }">
        <a-tag v-if="record.statusWbxqy === 'S'" color="blue">待审批</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'A'" color="green">已批准</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'R'" color="red">已拒绝</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'E'" color="gray">行程已结束</a-tag>
      </template>
      <template #operations="{ record,rowIndex }">
        <a-space>
          <a-button
              v-if="record.statusWbxqy==='S'"
              type="outline" @click="openShenPi(record)">
            <template #icon>
              <icon-edit/>
            </template>
            查看详情并审批
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 审批用车申请抽屉 -->
    <a-drawer
        :width="340"
        :visible="showShenPiDrawer"
        @ok="shenPiOk"
        @cancel="shenPiCancel"
        ok-text="同意并分配"
        cancel-text="拒绝并说明"
        unmountOnClose
    >
      <template #title>
        审批用车申请
      </template>
      <div>
        <!-- 展示用车申请信息 -->
        <div class="request-info">
          <p>申请人: {{ requestData.user.usernameWbxqy }}</p>
          <p>申请时间: {{ requestData.requestDateWbxqy }}</p>
          <p>开始时间: {{ requestData.startTimeWbxqy }}</p>
          <p>结束时间: {{ requestData.endTimeWbxqy }}</p>
          <p>状态:
            <a-tag v-if="requestData.statusWbxqy === 'S'" color="blue">待审批</a-tag>
            <a-tag v-else-if="requestData.statusWbxqy === 'A'" color="green">已批准</a-tag>
            <a-tag v-else-if="requestData.statusWbxqy === 'R'" color="red">已拒绝</a-tag>
            <a-tag v-else-if="requestData.statusWbxqy === 'E'" color="gray">行程已结束</a-tag>
          </p>
        </div>

        <!-- 审批和拒绝表单 -->
        <a-form :model="approvalForm" :rules="shenPiRules" ref="approvalFormRef" layout="vertical">
          <a-form-item label="分配司机" field="driverIdWbxqy">
            <a-select v-model="approvalForm.driverIdWbxqy" placeholder="请选择司机">
              <a-option v-for="driver in freeDrivers" :key="driver.userIdWbxqy" :value="driver.userIdWbxqy.toString()">
                {{ driver.usernameWbxqy }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="分配车辆" field="carIdWbxqy">
            <a-select v-model="approvalForm.carIdWbxqy" placeholder="请选择车辆">
              <a-option v-for="car in freeCars" :key="car.carIdWbxqy" :value="car.carIdWbxqy.toString()">
                {{ car.licensePlateWbxqy }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="拒绝理由" field="rejectResonWbxqy">
            <a-textarea v-model="approvalForm.rejectResonWbxqy" placeholder="请填写拒绝理由"/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </a-card>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {agreeCarRequest, getSCarRequests, listFreeCars, rejectCarRequest} from '@/api/carRequestMG';
import {IconSearch, IconRefresh, IconEdit} from '@arco-design/web-vue/es/icon';
import {listUsers} from "@/api/userMG";
import {listCars} from "@/api/carMG";
import {listFreeDrivers} from "@/api/driverMG";

const requests = ref([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});
const columns = [
  {title: '申请ID', dataIndex: 'requestIdWbxqy'},
  {title: '申请人', dataIndex: 'userIdWbxqy', slotName: 'user'},
  {title: '车辆', dataIndex: 'carIdWbxqy', slotName: 'car'},
  {title: '司机', dataIndex: 'driverIdWbxqy', slotName: 'driver'},
  {title: '申请日期', dataIndex: 'requestDateWbxqy'},
  {title: '开始时间', dataIndex: 'startTimeWbxqy'},
  {title: '结束时间', dataIndex: 'endTimeWbxqy'},
  {title: '申请状态', dataIndex: 'statusWbxqy', slotName: 'status'},
  {
    title: '操作',
    dataIndex: 'operation',
    width: '150',
    align: 'center',
    slotName: 'operations',
    fixed: 'right'
  }
];
// 搜索相关操作
const searchFormRef = ref(null);
const search_form = ref({
  userId: '',
  carId: '',
  driverId: '',
});
// 获取查询列表数据
const users = ref()
const cars = ref()
const drivers = ref()
const fetchUsers = async () => {
  // 请求用户列表的方法
  users.value = await listUsers({'role': 'U'})
}

const fetchCars = async () => {
  // 请求车辆列表的方法
  cars.value = await listCars()
}
const fetchDrivers = async () => {
  // 请求司机列表的方法
  drivers.value = await listUsers({'role': 'S'})
}
const handleSearchSubmit = async ({values, errors}) => {
  await fetchCarRequests(values);
};

const fetchCarRequests = async (params) => {
  console.log(params)
  let res = await getSCarRequests(params);
  requests.value = res.records;
  pagination.value.total = res.total;
  pagination.value.current = res.current;
};

const handlePaginationChange = async (page, pageSize) => {
  await fetchCarRequests({page, ...search_form.value});
};
// 审批相关操作
const showShenPiDrawer = ref(false)
const requestData = ref()

// 审批表单数据
// 审批表单数据
const approvalForm = reactive({
  driverIdWbxqy: null,
  carIdWbxqy: null,
  rejectResonWbxqy: '',
});
// 自定义验证规则，确保拒绝理由和其他字段不得同时填写
const validateDriverCarAndReason = (value, callback) => {
  if (approvalForm.rejectResonWbxqy && (approvalForm.driverIdWbxqy || approvalForm.carIdWbxqy)) {
    callback('拒绝理由和其他字段不得同时填写');
  } else if (!approvalForm.rejectResonWbxqy && (!approvalForm.driverIdWbxqy || !approvalForm.carIdWbxqy)) {
    callback('请填写分配司机和车辆或拒绝理由');
  } else {
    callback();
  }
}
// 表单验证规则
const shenPiRules = {
  driverIdWbxqy: [
    {validator: validateDriverCarAndReason, trigger: 'change'}
  ],
  carIdWbxqy: [
    {validator: validateDriverCarAndReason, trigger: 'change'}
  ],
  rejectResonWbxqy: [
    {validator: validateDriverCarAndReason, trigger: 'change'}
  ]
}
// 抽屉显示
const freeDrivers = ref()
const freeCars = ref()
const openShenPi = async (record) => {
  showShenPiDrawer.value = true;
  requestData.value = record
  freeDrivers.value = await listFreeDrivers(
      {'startTime': requestData.value.startTimeWbxqy, 'endTime': requestData.value.endTimeWbxqy})
  freeCars.value = await listFreeCars(
      {'startTime': requestData.value.startTimeWbxqy, 'endTime': requestData.value.endTimeWbxqy})
}
// 抽屉确认按钮事件
const approvalFormRef = ref();
const shenPiOk = () => {
  approvalFormRef.value.validate(async (valid) => {
    if (valid === undefined) {
      console.log("校验通过")
      if (approvalForm.rejectResonWbxqy) {
        // 提交拒绝审批表单逻辑
        console.log('拒绝审批:', approvalForm.rejectResonWbxqy);
        await rejectCarRequest(
            {
              "requestIdWbxqy": requestData.value.requestIdWbxqy,
              "rejectResonWbxqy": approvalForm.rejectResonWbxqy,
            },
        )
      } else {
        // 提交通过审批表单逻辑
        console.log('通过审批:', approvalForm);
        await agreeCarRequest(
            {
              "requestIdWbxqy": requestData.value.requestIdWbxqy,
              "carIdWbxqy": parseInt(approvalForm.carIdWbxqy),
              "driverIdWbxqy": parseInt(approvalForm.driverIdWbxqy)
            },
        )
      }
      await fetchCarRequests()
      showShenPiDrawer.value = false;
    }

  });
};

// 抽屉取消按钮事件
const shenPiCancel = () => {
  showShenPiDrawer.value = false;
};

onMounted(() => {
  fetchCarRequests();
  fetchUsers();
  fetchCars();
  fetchDrivers();
});
</script>

<style scoped>
</style>
